<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020-02-25
 * Time: 11:44
 */

namespace Zwwl2016\Cluster;


class ClusterCronTaskParameters
{
    private $parameterPairs=array();
    private $cron;
    private $clusterParameters;

    public function __construct()
    {

    }

    public static function Instance()
    {
        return new ClusterCronTaskParameters();
    }

    /**
     * @param ClusterCronTaskParameterPair $parameter
     * @return ClusterCronTaskParameters
     */
    public function add(ClusterCronTaskParameterPair $parameter)
    {
        $arr=[];
        $arr['cron']=$parameter->getCronString();
        $arr['parameter']=$parameter->getParametersArray();
        $this->parameterPairs[]=$arr;
        return $this;
    }


    public function getArray()
    {
        return $this->parameterPairs;
    }

    /**
     * @param $name
     * @param $arguments
     * @return ClusterCronTaskParameters
     * @throws \Exception
     */
    public function __call($name,$arguments)
    {
        $str=Utils::toUnderScore($name);

        if($this->clusterParameters==null)
        {
            $this->clusterParameters=ClusterParameters::Instance();
        }
        if($str=="cron")
        {
            if(empty($arguments))
            {
                throw new \Exception("no cron string");
            }
            if($this->cron!=null)
            {
                $this->build();
                $this->clusterParameters=ClusterParameters::Instance();
            }
            $this->cron=$arguments[0];
            return $this;
        }

        if($str=="where")
        {
            if(empty($arguments))
            {
                throw  new \Exception("where parameters empty!");
            }
            $this->clusterParameters->where($arguments[0]);
            return $this;
        }
        if($this->cron==null)
        {
            throw new \Exception("cron string is null ,please set by cron method !");
        }
        if($str=="table")
        {
            if(empty($arguments))
            {
                $this->clusterParameters->table();
            }
            else
            {
                $this->clusterParameters->table($arguments[0]);

            }

            return $this;
        }
        $this->clusterParameters->$str($arguments[0]);

        return $this;
    }

    /**
     * @return ClusterCronTaskParameters
     */
    public function build()
    {
        if($this->clusterParameters==null)
        {
            $this->clusterParameters=ClusterParameters::Instance();
        }
        $this->add(ClusterCronTaskParameterPair::Instance()
            ->setCronString($this->cron)
            ->setClusterParameters($this->clusterParameters->build()));
        return $this;
    }
}